package com.coocaa.aries.core.tool.http;

import com.alibaba.fastjson.JSON;
import com.coocaa.aries.core.base.exception.AriesException;
import com.coocaa.aries.core.base.exception.ExceptionUtil;
import com.coocaa.aries.core.tool.InstanceUtil;
import com.coocaa.aries.core.tool.json.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author bijiahao
 * @date : 2018/5/15.
 * @description
 */
@Slf4j
public class OkHttpUtil {

    /**
     * HTTP-POST请求-JSON数据
     *
     * @param httpUrl
     * @param data
     * @return
     */
    public static String postJsonData(String httpUrl, Object data) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody formBody = RequestBody.create(mediaType, JSON.toJSONString(data));
        String res = execute(httpUrl, formBody);
        return res;
    }

    /**
     * Http接口调用执行
     *
     * @param formBody
     * @return
     */
    public static String execute(String httpUrl, RequestBody formBody)  {
        Request request = new Request.Builder()
                .url(httpUrl)
                .post(formBody)
                .build();
        OkHttpClient client = new OkHttpClient();

        try {
            Response execute = client.newCall(request).execute();
            String result = execute.body().string();
            if (execute.isSuccessful()) {
                return result;
            }
            log.error(result);
        } catch (IOException e) {
             log.error(ExceptionUtil.getStackTraceAsString(e));
        }
        Map errMap = InstanceUtil.newHashMap(1);
        errMap.put("httpUrl", httpUrl);
        throw new AriesException("Http请求数据失败:" + JsonUtil.obj2Json(errMap));
    }

    public static void main(String[] args) {

    }
}
